<script setup>
import {reactive, ref } from 'vue'
import downloadList from './download-list.vue'
import {Greet, Download, Jd, MergeTs} from '../../wailsjs/go/main/App'

const data = reactive({
  name: "",
  folder: "C:\\Users\\Administrator\\Downloads",
  resultText: "",
  mergeText:""
})
let pollingInterval =null
// 新增一个响应式变量来表示下载状态
const isDownloading = ref(false)
function download() {
  if (isDownloading.value) return // 如果正在下载，不执行后续操作
  isDownloading.value = true // 开始下载，设置为 true
  Download(data.url,data.name,data.folder).then(result => {
    if (result.Code == 200){
      startPolling(result.Data, data.url)
    } else if(result.Code == 500) {
      data.resultText = result.Data
      isDownloading.value = false // 下载失败，设置为 false
    } else {
      startPolling(result.Data, data.url)
    }
  }).finally(() => {
      isDownloading.value = false // 无论下载成功还是失败，最终都设置为 false
  })
}
function fetchData(id, url){
   Jd(id, url).then(res => {
      data.resultText = res.Show
      isDownloading.value = true
      if(res.Finsh === 1) {
        stopPolling()
      }
   })
}
function mergeVideo(){
  MergeTs(data.url,data.name,data.folder).then(result => {
    data.mergeText = result
  })
}
function startPolling(id, url) {
    pollingInterval = setInterval(() => fetchData(id, url), 200); // 每0.2秒查询一次  
}

function stopPolling() {
    // 停止定时查询  
    if (pollingInterval !== null) {  
        clearInterval(pollingInterval);  
        pollingInterval = null; // 可选：将变量重置为null，表示没有正在运行的定时器
        isDownloading.value = false
    }  
}  
</script>
<template>
    <div id="right">
      
      <label>视频链接:</label>
      <input type="text" id="url" v-model="data.url" placeholder="视频链接">

      <label>视频名:</label>
      <input type="text" id="name" v-model="data.name" placeholder="视频名">
      
      <label>文件夹:</label>
      <input type="text" id="folder" v-model="data.folder"/>
      
      <div>
        <label>下载进度:</label>
        <div class="result">{{ data.resultText }}</div>
        <div class="result">{{ data.mergeText }}</div>
      </div>
      <div class="button-container">
        <button class="btn" :disabled="isDownloading" @click="download">下载</button>
        <button class="btn" @click="mergeVideo">强制合并视频</button>
      </div>
      <!-- <div>
        <downloadList/>
      </div> -->
    </div>
</template>
<style scoped>
/* 按钮容器样式 */
.button-container {
    display: flex;
    justify-content: center;
}
/* 可以根据需要调整按钮之间的间距 */
.button-container .btn {
    margin: 0 10px;
}
.btn:disabled {
    background-color: #ccc; /* 变灰的背景色 */
    color: #888; /* 变灰的文字颜色 */
    cursor: not-allowed; /* 鼠标样式为禁止 */
}
</style>